package top.zhdev.community.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.ognl.ASTProject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;
import top.zhdev.community.entity.Message;
import top.zhdev.community.entity.Page;
import top.zhdev.community.entity.User;
import top.zhdev.community.service.MessageService;
import top.zhdev.community.service.UserService;
import top.zhdev.community.utils.CommunityConstant;
import top.zhdev.community.utils.CommunityUtil;
import top.zhdev.community.utils.HostHolder;

import java.util.*;

/**
 * 私信处理器
 */
@Controller
public class MessageController implements CommunityConstant {

    private HostHolder hostHolder;
    private MessageService messageService;
    private UserService userService;

    @Autowired
    public void setHostHolder(HostHolder hostHolder){
        this.hostHolder = hostHolder;
    }

    @Autowired
    public void setMessageService(MessageService messageService){
        this.messageService = messageService;
    }

    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    /**
     * 获取私信列表
     * @param model
     * @param page
     * @return
     */
    @GetMapping("/letter/list")
    public String getLetterList(Model model, Page page){
        User user = hostHolder.getUser();
        // 分页信息
        page.setLimit(5);
        page.setPath("/letter/list");
        int count = messageService.getConversationCount(user.getId());
        page.setRows(count);

        // 会话列表
        List<Message> conversationList = messageService.getConversations(user.getId(),page.getOffset(),page.getLimit());
        List<Map<String,Object>> conversations = new ArrayList<>();
        if(conversationList != null){
            for (Message message:conversationList){
                Map<String,Object> map = new HashMap<>();
                map.put("conversation",message);
                map.put("letterCount",messageService.getLetterCount(message.getConversationId()));
                map.put("unreadCount",messageService.getLetterUnreadCount(user.getId(),message.getConversationId()));
                int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target",userService.getUserById(targetId));

                conversations.add(map);
            }
        }

        model.addAttribute("conversations",conversations);

        // 查询未读消息数量
        int letterUnreadCount = messageService.getLetterUnreadCount(user.getId(),null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);
        return "/site/letter";
    }

    /**
     * 获取系统通知列表
     * @param model
     * @return
     */
    @GetMapping("/notice/list")
    public String getNoticeList(Model model){
        User user = hostHolder.getUser();

        // 查询评论类通知
        Message message = messageService.getLatesNotice(user.getId(),TOPIC_COMMENT);
        setInfo(model,user,message,TOPIC_COMMENT);
        
        // 查询点赞类通知
        message = messageService.getLatesNotice(user.getId(),TOPIC_LIKE);
        setInfo(model,user,message,TOPIC_LIKE);

        //查询关注类通知
        message = messageService.getLatesNotice(user.getId(),TOPIC_FOLLOW);
        setInfo(model,user,message,TOPIC_FOLLOW);

        // 查询未读私信总数量，无会话id限制
        int letterUnreadCount = messageService.getLetterUnreadCount(user.getId(),null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);

        // 查询未读通知总数量，无topic限制
        int noticeUnreadCount = messageService.getNoticeUnreadCount(user.getId(),null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);

        return "/site/notice";
    }

    /**
     * 封装设置系统消息信息
     * @param model
     * @param user
     * @param message
     * @param topicType
     */
    private void setInfo(Model model,User user,Message message,String topicType){
        if(message != null){
            Map<String,Object> messageVo = new HashMap<>();
            messageVo.put("message",message);
            
            // 将转译字符还原回去
            String content = HtmlUtils.htmlUnescape(message.getContent());
            // 还原map
            Map<String,Object> data = JSONObject.parseObject(content,HashMap.class);
            messageVo.put("user",userService.getUserById((Integer) data.get("userId")));
            messageVo.put("entityType",data.get("entityType"));
            messageVo.put("entityId",data.get("entityId"));
            messageVo.put("postId",data.get("postId"));
            
            int count = messageService.getNoticeCount(user.getId(),topicType);
            messageVo.put("count",count);
            
            int unread = messageService.getNoticeUnreadCount(user.getId(),topicType);
            messageVo.put("unread",unread);

            switch (topicType){
                case TOPIC_COMMENT:
                    model.addAttribute("commentNotice",messageVo);
                    break;
                case TOPIC_LIKE:
                    model.addAttribute("likeNotice",messageVo);
                    break;
                case TOPIC_FOLLOW:
                    model.addAttribute("followNotice",messageVo);
            }
        }
    }

    /**
     * 发送私信
     * @param toName
     * @param content
     * @return
     */
    @PostMapping("/letter/send")
    @ResponseBody
    public String sendLetter(String toName,String content){
        User target = userService.getUserByName(toName);
        if(target == null){
            return CommunityUtil.getJSONString(1,"目标用户不存在");
        }

        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        if(message.getFromId() < message.getToId()){
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        }else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }

        message.setContent(content);
        message.setCreateTime(new Date());
        messageService.addMessage(message);
        return CommunityUtil.getJSONString(0);
    }

    /**
     * 私信详情
     * @param conversationId
     * @param page
     * @param model
     * @return
     */
    @GetMapping("/letter/detail/{conversationId}")
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Page page, Model model){
        // 分页信息
        page.setLimit(5);
        page.setPath("/letter/detail/" + conversationId);
        page.setRows(messageService.getLetterCount(conversationId));

        // 私信列表
        List<Message> letterList = messageService.getLetters(conversationId,page.getOffset(),page.getLimit());
        List<Map<String,Object>> letters = new ArrayList<>();
        if(letterList != null){
            for (Message message : letterList){
                Map<String,Object> map = new HashMap<>();
                map.put("letter",message);
                map.put("fromUser",userService.getUserById(message.getFromId()));
                letters.add(map);
            }
        }
        model.addAttribute("letters",letters);

        // 私信目标
        model.addAttribute("target",getLetterTarget(conversationId));

        // 设置已读
        List<Integer> ids = getLetterIds(letterList);
        if(! ids.isEmpty()){
            messageService.readMessage(ids);
        }

        return "/site/letter-detail";
    }


    /**
     * 获取系统通知详情页（展示所有系统通知）
     * @param topic
     * @param page
     * @param model
     * @return
     */
    @GetMapping("/notice/detail/{topic}")
    public String getNoticeDetail(@PathVariable("topic") String topic, Page page, Model model){
        User user = hostHolder.getUser();

        page.setLimit(5);
        page.setPath("/notice/detail/" + topic);
        page.setRows(messageService.getNoticeCount(user.getId(),topic));

        List<Message> noticeList = messageService.getNotices(user.getId(),topic,page.getOffset(),page.getLimit());
        List<Map<String,Object>> noticeVo = new ArrayList<>();
        if(noticeList != null){
            for(Message notice : noticeList){
                Map<String,Object> map = new HashMap<>();
                // 通知
                map.put("notice",notice);
                //内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String,Object> data = JSONObject.parseObject(content,HashMap.class);
                map.put("user",userService.getUserById((Integer)data.get("userId") ) );
                map.put("entityType",data.get("entityType"));
                map.put("entityId",data.get("entityId"));
                map.put("postId",data.get("postId"));
                map.put("fromUser",userService.getUserById(notice.getFromId()));
                noticeVo.add(map);
            }
        }
        model.addAttribute("notices",noticeVo);

        // 设置已读
        List<Integer> ids = getLetterIds(noticeList);
        if(! ids.isEmpty()){
            messageService.readMessage(ids);
        }

        return "/site/notice-detail";
    }


    /**
     * 获取私信发送的目标用户
     * @param conversationId
     * @return
     */
    private User getLetterTarget(String conversationId){
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);

        if(hostHolder.getUser().getId() == id0){
            return userService.getUserById(id1);
        }else {
            return userService.getUserById(id0);
        }
    }

    /**
     * 获取未读的消息列表
     * @param letterList
     * @return
     */
    private List<Integer> getLetterIds(List<Message> letterList){
        List<Integer> ids = new ArrayList<>();

        if(letterList != null){
            for(Message message : letterList){
                if(hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0){
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }
}
